/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.leo.ibatis.demo.base;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.springframework.util.FileCopyUtils;

/**
 * Attach file persister.
 * 
 * @author Byeongkil Woo
 */
public class AttachFilePersister {

	public static void saveFile(File saveDir, AttachFile attachFile) {
		File file = new File(saveDir, attachFile.getName());

		try {
			file.createNewFile();
			FileCopyUtils.copy(attachFile.getBytes(), file);
		}
		catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static int saveFiles(File saveDir, Collection<AttachFile> attachFiles) {
		Collection<AttachFile> savedFiles = new ArrayList<AttachFile>(attachFiles.size());

		try {
			Iterator<AttachFile> i = attachFiles.iterator();
			while (i.hasNext()) {
				AttachFile attachFile = i.next();

				if (attachFile != null) {
					saveFile(saveDir, attachFile);
					savedFiles.add(attachFile);
				}
			}
		}
		catch (RuntimeException e) {
			if (savedFiles.size() > 0) {
				deleteFiles(saveDir, savedFiles);
			}

			throw e;
		}

		return savedFiles.size();
	}

	public static boolean deleteFile(File saveDir, AttachFile attachFile) {
		if (attachFile == null || attachFile.getName() == null) {
			return false;
		}
		
		boolean deleted = false;

		File file = new File(saveDir, attachFile.getName());

		if (file.exists()) {
			deleted = file.delete();
		}

		return deleted;
	}

	public static int deleteFiles(File saveDir, Collection<AttachFile> attachFiles) {
		int deletedCount = 0;

		Iterator<AttachFile> i = attachFiles.iterator();
		while (i.hasNext()) {
			AttachFile attachFile = i.next();

			if (deleteFile(saveDir, attachFile)) {
				deletedCount++;
			}
		}

		return deletedCount;
	}

}
